import { Hono } from "hono";
import { z } from "zod";
import validator from "../middlewares/validate";
import { HealthService } from "../services/health";
import Responder from "../middlewares/response";
import { authMiddleware } from "../middlewares/auth";

const health = new Hono();
const healthService = new HealthService();

health.use("*", authMiddleware);

// 验证 schema
const healthRecordSchema = z.object({
  recordType: z.enum(["weight", "bloodPressure", "heartRate", "sleepQuality"]),
  details: z.object({
    weight: z
      .object({
        value: z.number(),
        unit: z.enum(["kg", "lb"]),
      })
      .optional(),
    bloodPressure: z
      .object({
        systolic: z.number(),
        diastolic: z.number(),
        pulse: z.number().optional(),
      })
      .optional(),
    heartRate: z
      .object({
        current: z.number(),
        max: z.number().optional(),
        min: z.number().optional(),
        avg: z.number().optional(),
      })
      .optional(),
    sleepQuality: z
      .object({
        totalSleepDuration: z.number(),
        sleepStartTime: z.string().optional(),
        wakeUpTime: z.string().optional(),
      })
      .optional(),
  }),
  remark: z.string().optional(),
  source: z.enum(["manual", "device"]),
  deviceId: z.string().optional(),
});

// 获取健康记录列表
health.get("/records", async (c) => {
  const userId = c.get("userId");
  const { recordType, startDate, endDate, limit, skip } = c.req.query();

  const options = {
    recordType: recordType as
      | "weight"
      | "bloodPressure"
      | "heartRate"
      | "sleepQuality"
      | undefined,
    startDate: startDate ? new Date(startDate) : undefined,
    endDate: endDate ? new Date(endDate) : undefined,
    limit: limit ? parseInt(limit) : undefined,
    skip: skip ? parseInt(skip) : undefined,
  };

  const result = await healthService.getRecords(userId, options);
  return Responder.success().setData(result).build(c);
});

// 创建健康记录
health.post("/records", validator("json", healthRecordSchema), async (c) => {
  const userId = c.get("userId");
  const data = c.req.valid("json");

  const result = await healthService.createRecord({
    ...data,
    userId,
    timestamp: new Date(),
  });

  return Responder.success("健康记录创建成功").setData(result).build(c);
});

// 获取单个健康记录
health.get("/records/:id", async (c) => {
  const userId = c.get("userId");
  const recordId = c.req.param("id");

  const result = await healthService.getRecord(userId, recordId);
  return Responder.success().setData(result).build(c);
});

// 更新健康记录
health.put("/records/:id", validator("json", healthRecordSchema), async (c) => {
  const userId = c.get("userId");
  const recordId = c.req.param("id");
  const data = c.req.valid("json");

  const result = await healthService.updateRecord(userId, recordId, data);
  return Responder.success("健康记录更新成功").setData(result).build(c);
});

// 删除健康记录
health.delete("/records/:id", async (c) => {
  const userId = c.get("userId");
  const recordId = c.req.param("id");

  await healthService.deleteRecord(userId, recordId);
  return Responder.success("健康记录删除成功").build(c);
});

// 获取健康趋势数据
health.get("/stats/trends", async (c) => {
  const userId = c.get("userId");
  const { recordType, startDate, endDate } = c.req.query();

  if (!recordType || !startDate || !endDate) {
    return Responder.fail("缺少必要的查询参数").build(c);
  }

  const result = await healthService.getHealthTrends(
    userId,
    recordType as "weight" | "bloodPressure" | "heartRate" | "sleepQuality",
    new Date(startDate),
    new Date(endDate)
  );

  return Responder.success().setData(result).build(c);
});

export default health;
